package com.iot.ht.controller.htmenu.service;

import com.iot.core.data.BaseQto;
import com.iot.core.data.entity.HtMenu;
import com.iot.core.data.mapper.*;
import com.iot.core.data.service.ServiceImpl;
import com.iot.ht.controller.htmenu.data.HtMenuDto;
import com.iot.ht.controller.htmenu.data.HtMenuInsertQto;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import static com.iot.core.data.entity.table.HtMenuTableDef.HT_MENU;
import static com.mybatisflex.core.query.QueryMethods.ifNull;
import static com.mybatisflex.core.query.QueryMethods.max;

@Slf4j
@Service
public class HtMenuService extends ServiceImpl<HtMenuMapper, HtMenu> implements IHtMenuService {
    @Autowired
    HtDbMapper htdbMapper;
    @Autowired
    HtPageMapper htPageMapper;
    @Autowired
    HtCtlMapper htCtlMapper;
    @Autowired
    HtActionMapper htActionMapper;
    @Override
    public HtMenuDto insertInit(HtMenuInsertQto qm){
        var mm=new HtMenuDto();
        mm.setPid(qm.getId());
        mm.setHtplatId(qm.getHtplatId());
        mm.setLx(qm.getLx());
        mm.setImgurl("layui-icon-spread-left");
        var qw=getBaseMapper().getQueryWrapper();
        qw.select(     max(HT_MENU.SORTNO) )
            .where( HT_MENU.HTPLAT_ID.eq(qm.getHtplatId()).and(  HT_MENU.PID.eq( mm.getPid()  ) ) );
        var sortno=getBaseMapper().selectOneByQueryAs(qw,Long.class);
        if(ObjectUtils.isEmpty(sortno)){
            sortno=0L;
        }
        sortno+=10;
        mm.setSortno(sortno );
        return mm;
    }
    @Override
    public HtMenuDto detail(BaseQto qm){
        var m=getById(qm);
        var mm=new HtMenuDto();

        getBaseMapper().entityToDto(m,mm);
        if(m.getHtpageId()>0){
            var mpage=htPageMapper.getById(m.getHtpageId() );
            mm.setCode(mpage.getCode());
            mm.setP1(mpage.getP1()  );
            mm.setP2(mpage.getP2()  );
            mm.setP3(mpage.getP3()  );
            mm.setP4(mpage.getP4()  );
        }

        return mm;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(HtMenuDto mm){

        var m = new  HtMenu();
        getBaseMapper().dtoToEntity(mm,m);

        return   insert(m );

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public   int update(HtMenuDto mm){
        var m = getById(mm.getId() );
        getBaseMapper().dtoToEntity(mm,m);

        return  updateById(m );
    }
}
